import axios from "axios"
import store from '../store'
import { getToken } from '@/utils/auth'
import { Notification, MessageBox } from 'element-ui'
import Config from '@/settings'
const baseURL = process.env.NODE_ENV === 'production' ? window.location.origin + '/' : process.env.VUE_APP_BASE_API;
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8"

// 创建axios实例
const service = axios.create({
	// axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: baseURL,
  withCredentials: true,
  'X-Requested-With': null,
	// 超时设置为10秒
	timeout: 10000
})
// request拦截器
service.interceptors.request.use(
	config => {
		if (getToken()) {
      config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.headers['Content-Type'] = 'application/json'
    if(config.url.includes('device/upgrade')) {
      config.timeout = 30 * 60 * 1000
    }else if(config.url.includes('addOrUpdateProject')
      || config.url.includes('updateMonitor')
      || config.url.includes('updateGbInfo')
      || config.url.includes('dataSync')
      || config.url.includes('rebootSystem')
      || config.url.includes('replaceDevice')
      || config.url.includes('searchDevice')){
      config.timeout = 3 * 60 * 1000
    }else if(config.url.includes('getDeviceList') || config.url.includes('getDeviceAndUnitInfo')){
      config.timeout = 30 * 1000
    }else{
      config.timeout = 10 * 1000
    }
    return config
	},
	error => {
		console.log(error)
    Promise.reject(error)
	}
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const code = response.status
    if (code < 200 || code > 300) {
      Notification.error({
        title: response.message
      })
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    let code = 0
    try {
      code = error.response.data.status
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        this.loading = false;
        return Promise.reject(error)
      }
    }
    if (code) {
      if (code === 401) {
        MessageBox.alert(
          '登录状态已过期，您可以继续留在该页面，或者重新登录',
          '系统提示',
          {
            confirmButtonText: '重新登录',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      } else if (code === 403) {
        router.push({ path: '/401' })
      } else {
        const errorMsg = error.response.data.message
        if (errorMsg !== undefined) {
          Notification.error({
            title: errorMsg,
            duration: 5000
          })
        }
      }
    } else {
      Notification.error({
        title: '接口请求失败',
        duration: 5000
      })
    }
    return Promise.reject(error)
  }
)


export function _get (url, data, callback, errCallback=null) {
    var configObj = {
        method   : "GET",
        url      : baseURL + url,
        async    : true,
        data     : data,
        dataType : 'json',
        success  : callback,
        error    : function(msg){  }
    };
    if(data){
        service.get(configObj.url+'?'+data).then((res)=>{
        if (typeof(callback) === 'function') {
          if (res.code == 0) {
            let resp = res
            resp.data = res.data?JSON.parse(res.data): ''
            callback(resp);
          }else{
            callback(res)
          }
        }
      }).catch((err)=>{
        if(errCallback){
          errCallback(err)
        }
      })
    }else{
        service.get(configObj.url).then((res)=>{
        if (typeof(callback) === 'function') {
          if (res.code == 0) {
            let resp = res
            resp.data = res.data?JSON.parse(res.data): ''
            callback(resp);
          }else{
            callback(res)
          }
        }
      }).catch((err)=>{
        if(errCallback){
          errCallback(err)
        }
      })
    }
}

  export function _post (url, data, callback, errCallback=null) {
    var configObj = {
        method   : "POST",
        url      : baseURL + url,
        async    : true,
        data     : data,
        dataType : "application/json",
        success  : callback,
        error    : function(msg){  }
      };
      if(data){
        service.post(configObj.url,data, { headers: {"content-type": "application/json"} }).then((res) =>{
            callback(res)
        }).catch((err)=>{
          if(errCallback){
            errCallback(err)
          }
        });
      }
  }

  export function _delete (url, data, callback, errCallback=null) {
    var configObj = {
        method   : "DELETE",
        url      : baseURL + url,
        async    : true,
        data     : data,
        dataType : 'application/json',
        success  : callback,
        error    : function(msg){  }
    };
    if(data){
      service.delete(configObj.url,{data: data}, { headers: {"content-type": "application/json"} }).then((res)=>{
          callback(res)
      }).catch((err)=>{
        if(errCallback){
          errCallback(err)
        }
      })
    }
  }

  export function _put (url, data, callback, errCallback=null) {
    var configObj = {
        method   : "PUT",
        url      : baseURL + url,
        async    : true,
        data     : data,
        dataType : "application/json",
        success  : callback,
        error    : function(msg){  }
      };
      // $.ajax(configObj);
      service.put(configObj.url,data, { headers: {"content-type": "application/json"} }).then((res) =>{
          callback(res)
      }).catch((err)=>{
        if(errCallback){
          errCallback(err)
        }
      });
  }

  export function _download(url, callback, errCallback=null) {
    var configObj = {
      method   : "GET",
      url      : baseURL + url,
  };
    service.get(configObj.url,{responseType: 'blob'}).then((res)=>{
      if (typeof(callback) === 'function') {
        if (res.code == 0) {
          let resp = res
          resp.data = res.data?JSON.parse(res.data): ''
          callback(resp);
        }else{
          callback(res)
        }
      }
    }).catch((err)=>{
      if(errCallback){
        errCallback(err)
      }
    })
  }
